package com.gitee.jmash.rbac.utils;

import org.eclipse.microprofile.config.inject.ConfigProperties;
import org.eclipse.microprofile.jwt.JsonWebToken;
import com.gitee.jmash.common.cache.SerialCache;
import com.gitee.jmash.common.utils.UUIDUtil;
import com.gitee.jmash.core.security.JmashJwtClaimsBuilder;
import com.gitee.jmash.rbac.AuthProps;
import com.gitee.jmash.rbac.client.shiro.JmashJsonWebToken;
import com.gitee.jmash.rbac.entity.UserEntity;
import io.smallrye.jwt.build.Jwt;
import jakarta.enterprise.inject.spi.CDI;

public class TokenUtil {

  /** 缓存. */
  public static SerialCache getCache() {
    return CDI.current().select(SerialCache.class).get();
  }

  public static AuthProps getAuthProps() {
    return CDI.current().select(AuthProps.class, ConfigProperties.Literal.NO_PREFIX).get();
  }

  /** 创建系统访问Token. */
  public static String createSysAccessToken(String tenant) {
    String key = "systoken:" + tenant;
    if (getCache().containsKey(key)) {
      return (String) getCache().get(key);
    }
    JsonWebToken webToken =
        createJsonWebToken(tenant, UUIDUtil.emptyUUID32(), null, null, null, "system", null);
    String accessToken = Jwt.claims(webToken).innerSign().encrypt();
    getCache().put(key, accessToken, getAuthProps().getExpiresIn() - 300);
    return accessToken;
  }

  /** 创建ClientToken(过期秒). */
  public static JsonWebToken createClientToken(String tenant, String clientId, String scope) {
    String principalName = UUIDUtil.emptyUUID32();
    return createJsonWebToken(tenant, principalName, null, null, "client", clientId, scope);
  }

  /** 创建JsonWebToken(过期秒). */
  public static JsonWebToken createJsonWebToken(String tenant, UserEntity user, String storage,
      String clientId, String subject, String scope) {
    String principalName = UUIDUtil.uuid32(user.getUserId());
    return createJsonWebToken(tenant, principalName, user.getUnifiedId(), storage, clientId,
        subject, scope);
  }

  /** 创建JsonWebToken(过期秒). */
  public static JsonWebToken createJsonWebToken(String tenant, String principalName,
      String unifiedId, String storage, String clientId, String subject, String scope) {
    JmashJwtClaimsBuilder builder = JmashJwtClaimsBuilder.newBuilder();
    // 租户.
    builder.setTenant(tenant);
    // 个人信息存储区.
    builder.setStorage(storage);
    // unique principal name.
    builder.setName(principalName);
    // unifiedId生态ID
    builder.setUnifiedId(unifiedId);
    // 登录用户名/手机号/电子邮件地址.
    builder.setSubject(subject);
    // 被授权方.
    builder.setClientId(clientId);
    // 授权范围.
    builder.setScope(scope);
    // 设置过期秒数
    builder.setExpiresIn(getAuthProps().getExpiresIn());
    JsonWebToken jsonWebToken = new JmashJsonWebToken(builder.getJwtClaims());
    return jsonWebToken;
  }

}
